﻿using System;
using System.Collections.ObjectModel;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MySQL.Db;
using MySql.Data.MySqlClient;

namespace Gollie.Ajax
{
	public class VendorGetCashClose : AjaxResult
	{
		public Collection<CashClosing> CashClosings = new Collection<CashClosing>();
		public decimal OpenAmount;

		public VendorGetCashClose() : base(null) { }

		public VendorGetCashClose(AjaxArg arg)
			: base(arg)
		{
		}

		protected override void Init(AjaxArg arg)
		{
			uint uid = Convert.ToUInt32(arg.tokenUser);

			try
			{
				ResultSetCollection r = Database.Queries.GetLatestCashClose(uid);

				ResultSet rClosings = r[0];
				ResultSet rOpenAmount = r[1];

				for (int i = 0; i < rClosings.Count; i++)
				{
					DateTime dt = rClosings.GetDateTime(i, "closedate");
					decimal amount = rClosings.GetDecimal(i, "amount");

					CashClosings.Add(new CashClosing() { Amount = amount, ClosingTime = dt.ToString("dd-MM-yy, HH:mm:ss") });
				}

				OpenAmount = -rOpenAmount.GetDecimal(0, "openamount");
			}
			catch (MySqlException mySqlEx)
			{
				this.ErrorCode = mySqlEx.Number;
				this.ErrorMessage = MySqlErrorCodes.GetInstance().GetMessage(mySqlEx);
				logger.Info("VendorGetCashClose failed for userid {0}: {1}", uid, this.ErrorMessage);
			}
			catch (Exception e)
			{
				if (this.ErrorCode == 0)
					this.ErrorCode = 99;

				this.ErrorMessage = e.Message;
				logger.Info("VendorGetCashClose failed for userid {0}: {1}", uid, this.ErrorMessage);
			}
		}
	}

	public class CashClosing
	{
		public decimal Amount;
		public string ClosingTime;
	}
}